<template>
  <!-- 角色表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="800px"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      inline="true"
    >
      <el-form-item label="方案代码" prop="schemeCode">
        <el-input
          v-if="!props.isReadonly"
          v-model="formData.schemeCode"
          placeholder="请输入方案代码"
          clearable
        />
        <span v-else>{{ formData.schemeCode }}</span>
      </el-form-item>
      <el-form-item label="方案名称" prop="schemeName">
        <el-input
          v-if="!props.isReadonly"
          v-model="formData.schemeName"
          placeholder="请输入方案名称"
          clearable
        />
        <span v-else>{{ formData.schemeName }}</span>
      </el-form-item>
      <el-form-item label="业务领域" prop="businessDomain">
        <el-select
          v-if="!props.isReadonly"
          v-model="formData.businessDomain"
          placeholder="请选择业务领域"
          clearable
        >
          <el-option
            v-for="item in dictionaryStore.filterDictList('BusinessDomain')"
            :key="item.value"
            :label="item.label"
            :value="Number(item.value)"
          />
        </el-select>

        <span v-else>{{
          dictionaryStore.filterDictName(
            "BusinessDomain",
            formData.businessDomain
          )
        }}</span>
      </el-form-item>
      <el-form-item label="检测类别" prop="checkTypeId">
        <el-select
          v-if="!props.isReadonly"
          v-model="formData.checkTypeId"
          @change="checkTypeChange"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="item in checkTypes"
            :key="item.id"
            :label="item.checkTypeName"
            :value="item.id"
          />
        </el-select>
        <span v-else>{{ formData.checkTypeId }}</span>
      </el-form-item>
      <el-form-item label="公司">
        <SelectOriganization
          :selectData="formData.organizationId"
          :isCheckStrictly="true"
          @change="getSelectIds"
          @change-data="organizationDataChange"
          :isMultiple="false"
        />
      </el-form-item>
      <el-form-item label="工厂">
        <el-select
          v-if="!props.isReadonly"
          @change="plantChange"
          v-model="formData.plantId"
          placeholder="请选择"
        >
          <el-option
            v-for="item in plants"
            :key="item.id"
            :label="item.plantName"
            :value="item.id"
          />
        </el-select>
        <span v-else>{{ formData.plantId }}</span>
      </el-form-item>
      <el-form-item label="备注" style="width: 650px">
        <el-input
          v-if="!props.isReadonly"
          type="textarea"
          v-model="formData.remarks"
          placeholder="请输入备注"
          clearable
        />

        <span v-else>{{ formData.remarks }}</span>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MDMCHECKSCHEMEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

const rules = reactive({
  schemeCode: [{ required: true, message: "请输入方案代码", trigger: "blur" }],
  schemeName: [{ required: true, message: "请输入方案名称", trigger: "blur" }],
  businessDomain: [
    { required: true, message: "请输入业务领域", trigger: "blur" },
  ],
  checkTypeId: [{ required: true, message: "请输入检测类别", trigger: "blur" }],
  organizationId: [{ required: true, message: "请输入公司", trigger: "blur" }],
  plantId: [{ required: true, message: "请输入工厂id", trigger: "blur" }],
  version: [{ required: true, message: "请输入数据版本号", trigger: "blur" }],
  remarks: [{ required: true, message: "请输入备注", trigger: "blur" }],
});

const formRef = ref(ElForm);
let checkTypes = ref([]);
let plants = ref([]);
let formData = reactive({
  id: "",
  schemeCode: "",
  schemeName: "",
  businessDomain: "",
  checkTypeId: "",
  checkTypeCode: "",
  checkTypeName: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        schemeCode,
        schemeName,
        businessDomain,
        checkTypeId,
        checkTypeName,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
      } = newVal;
      Object.assign(formData, {
        id,
        schemeCode,
        schemeName,
        businessDomain,
        checkTypeId,
        checkTypeName,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        version,
        createTime,
        createdUserId,
        createdUserName,
        remarks,
      });
      console.log("formData", formData);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.schemeCode = "";
  formData.businessDomain = "";
  formData.checkTypeId = "";
  formData.checkTypeName = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
}

const loading = ref(false);

/** 检测方案保存提交 */
function handleSubmit() {
  console.log("11111111111");
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mdm/checkscheme/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

/** 检测方案查询详细表 */
async function getDatails() {
  const data = await request({
    url: "/mdm/checkscheme/getDetails",
    method: "post",
    data: formData,
  });
  console.log(data);
}

onMounted(() => {
  getCheckTypes();
  if (formData.id) {
    getDatails();
  }
});

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
function getSelectIds(ids) {
  formData.organizationId = ids;
  getPlants();
}
function organizationDataChange(datas: [] | {}) {
  formData.organizationName = datas.organizationName;
  formData.organizationCode = datas.organizationCode;
}
async function getCheckTypes() {
  const data = await request({
    url: "/mdm/checktype/getList",
    method: "post",
    data: {},
  });
  checkTypes.value = data.data;
}
async function getPlants() {
  const data = await request({
    url: "/mdm/plant/getList",
    method: "post",
    data: { organizationId: formData.organizationId },
  });
  plants.value = data.data;
}
async function plantChange() {
  const data = plants.value.filter((item) => item.id === formData.plantId)[0];
  formData.plantCode = data.plantCode;
  formData.plantName = data.plantName;
}
async function checkTypeChange() {
  const data = checkTypes.value.filter(
    (item) => item.id === formData.checkTypeId
  )[0];
  formData.checkTypeCode = data.checkTypeCode;
  formData.checkTypeName = data.checkTypeName;
}
</script>
